<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateRolePermissionTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        // 角色表
        Schema::create('roles', function (Blueprint $table) {
            $table->increments('id');

            // 角色名
            $table->string('name')->unique();

            // 角色显示名
            $table->string('display_name')->nullable();

            // 角色描述
            $table->string('description')->nullable();


            $table->timestamps();
        });

        // 角色和用户关联表
        Schema::create('administrator_role', function (Blueprint $table) {
            $table->integer('administrator_id')->unsigned();
            $table->integer('role_id')->unsigned();

            // 设置外键
            $table->foreign('administrator_id')->references('id')->on('administrators')
                ->onUpdate('cascade')->onDelete('cascade');
            $table->foreign('role_id')->references('id')->on('roles')
                ->onUpdate('cascade')->onDelete('cascade');

            $table->primary(['administrator_id', 'role_id']);
        });

        // 授权表
        Schema::create('permissions', function (Blueprint $table) {
            $table->increments('id');

            // 授权名
            $table->string('name')->unique();

            // 授权显示名
            $table->string('display_name')->nullable();

            // 授权描述
            $table->string('description')->nullable();

            $table->timestamps();
        });

        // 角色授权关联表
        Schema::create('permission_role', function (Blueprint $table) {
            $table->integer('permission_id')->unsigned();
            $table->integer('role_id')->unsigned();

            $table->foreign('permission_id')->references('id')->on('permissions')
                ->onUpdate('cascade')->onDelete('cascade');
            $table->foreign('role_id')->references('id')->on('roles')
                ->onUpdate('cascade')->onDelete('cascade');

            $table->primary(['permission_id', 'role_id']);
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::drop('permission_role');
        Schema::drop('permissions');
        Schema::drop('administrator_role');
        Schema::drop('roles');
    }
}
